<!--
 * Description: double click 组件
 * Company: 联宝（合肥）电子科技有限公司
 * Author: Qiuxue.Wu
 * Date: 2020/06/15 09:33
-->

<template>
  <div class="base-dbl-click" @dblclick="dblclick">
    <div v-if="!isDblClick" class="one">
      <slot name="one" />
      <img class="update-icon" :src="updateIcon" @click="dblclick" />
    </div>
    <div v-else class="two">
      <slot name="two" />
    </div>
  </div>
</template>
<script>
import updateIcon from '@/assets/icons/update.png'
export default {
  name: 'BaseDblClick',
  props: {
    scope: {
      default: () => null,
      type: Object
    }
  },
  data() {
    return {
      updateIcon: updateIcon,
      copyData: null,
      isDblClick: false
    }
  },
  watch: {
    isDblClick: {
      handler() {
        this.copyData = this.$deepCopy(this.scope.row)
      }
    }
  },
  mounted() {
    window.addEventListener('click', this.clickHandler)
  },
  beforeDestroy() {
    window.removeEventListener('click', this.clickHandler)
  },
  methods: {
    dblclick() {
      this.isDblClick = !this.isDblClick
    },

    clickHandler(e) {
      const selectDom = e.path.find(dom => dom.className === 'base-dbl-click')
      if (!selectDom && !this.isDblClick) return
      // 冒泡不经过的时候同时第二个slot是显示的状态
      if (!selectDom && this.isDblClick) {
        this.isDblClick = false
        const isChange = JSON.stringify(this.copyData) !== JSON.stringify(this.scope.row)
        if (isChange) this.$emit('updateCell', this.scope)
        return
      }
      const isSame =
        selectDom.getBoundingClientRect().x === this.$el.getBoundingClientRect().x &&
        selectDom.getBoundingClientRect().y === this.$el.getBoundingClientRect().y
      if (selectDom && !isSame && this.isDblClick) {
        this.isDblClick = false
        const isChange = JSON.stringify(this.copyData) !== JSON.stringify(this.scope.row)
        if (isChange) this.$emit('updateCell', this.scope)
        return
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.base-dbl-click {
  width: 100%;
  height: 100%;
  .one,
  .two {
    width: 100%;
    height: 100%;
    position: relative;
  }
  .one {
    position: relative;
  }
  .update-icon {
    position: absolute;
    top: 4px;
    right: 4px;
    width: 12px;
    height: 12px;
    cursor: pointer;
  }
}
</style>
